package com.atguigu.service.impl;

import com.atguigu.common.config.exception.MyException;
import com.atguigu.mapper.SysMenuMapper;
import com.atguigu.mapper.SysRoleMenuMapper;
import com.atguigu.model.system.SysMenu;
import com.atguigu.model.system.SysUser;
import com.atguigu.security.custom.CustomUser;
import com.atguigu.service.SysMenuService;
import com.atguigu.service.SysRoleMenuService;
import com.atguigu.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserService.getOne(wrapper);
        if (null==sysUser){
            throw new MyException(201,"用户不存在");
        }
        if (sysUser.getStatus()==0){
            throw new MyException(201,"账户已停用");
        }
        //修改部分
        List<SysMenu> allMenusByUserId=new ArrayList<>();
        if(sysUser.getId().intValue()==1){
            allMenusByUserId=sysMenuMapper.selectList(null);
        }else{
        allMenusByUserId = sysMenuMapper.getAllMenusByUserId(sysUser.getId());
        }
        List<String> permsList = sysMenuService.getPermsList(allMenusByUserId, sysUser.getId());
        if (CollectionUtils.isEmpty(permsList)){
            return new CustomUser(sysUser,Collections.emptyList());
        }else {
            List<SimpleGrantedAuthority> collect = permsList.stream().map(perm -> new SimpleGrantedAuthority(perm)).collect(Collectors.toList());
            return new CustomUser(sysUser, collect);
        }
    }
}
